# 1. 无参数函数
def greet():
    """打印问候语（无参数无返回值）"""
    print("Hello, World!")

greet()  # 调用函数

# 2. 带返回值函数
def get_pi():
    """返回圆周率（无参数有返回值）"""
    return 3.1415926

pi = get_pi()  # 接收返回值
print(f"圆周率: {pi:.2f}")  # 圆周率: 3.14



def power(base, exponent):
    """计算幂（位置参数必须按顺序传递）"""
    return base ** exponent

print(power(2, 3))  # 8（2的3次方）
print(power(3, 2))  # 9（3的2次方）




def divide(dividend, divisor):
    """除法运算（明确指定参数名）"""
    return dividend / divisor

print(divide(divisor=2, dividend=10))  # 5.0（顺序不影响）







def greet(name, greeting="Hello"):
    """带默认值的问候函数"""
    return f"{greeting}, {name}!"

print(greet("Alice"))          # Hello, Alice!
print(greet("Bob", "Hi"))      # Hi, Bob!





def sum_all(*numbers):
    """求任意数量的数字和"""
    total = 0
    for num in numbers:
        total += num
    return total

print(sum_all(1, 2, 3))       # 6
print(sum_all(1, 2, 3, 4, 5)) # 15

def print_info(**details):
    """打印键值对信息"""
    for key, value in details.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=25, city="New York")
# name: Alice
# age: 25
# city: New York






def analyze_numbers(numbers):
    """返回列表的最大值、最小值和平均值"""
    return max(numbers), min(numbers), sum(numbers)/len(numbers)

max_num, min_num, avg = analyze_numbers([4, 2, 9, 5])
print(f"最大值: {max_num}, 最小值: {min_num}, 平均值: {avg:.1f}")
# 最大值: 9, 最小值: 2, 平均值: 5.0









def make_multiplier(factor):
    """生成一个乘数函数"""
    def multiplier(x):
        return x * factor
    return multiplier

double = make_multiplier(2)
print(double(5))  # 10




def no_return():
    """没有return语句的函数"""
    pass

result = no_return()
print(result)  # None





def add_item(item, items=[]):  # 默认参数是可变对象
    items.append(item)
    return items

print(add_item(1))  # [1]
print(add_item(2))  # [1, 2] （不是预期的[2]！）

# 正确写法：
def add_item_fixed(item, items=None):
    items = items or []  # 每次创建新列表
    items.append(item)
    return items




def mixed_args(a, b, c=0, *args, **kwargs):
    print(f"a={a}, b={b}, c={c}, args={args}, kwargs={kwargs}")

mixed_args(1, 2, 3, 4, 5, name="Alice")
# a=1, b=2, c=3, args=(4, 5), kwargs={'name': 'Alice'}


def convert_temp(temp, from_scale='c', to_scale='f'):
    """温度单位转换
    Args:
        temp: 温度值
        from_scale: 原单位 ('c'-摄氏, 'f'-华氏, 'k'-开尔文)
        to_scale: 目标单位
    Returns:
        转换后的温度值
    """
    # 先统一转为摄氏温度
    if from_scale.lower() == 'f':
        celsius = (temp - 32) * 5 / 9
    elif from_scale.lower() == 'k':
        celsius = temp - 273.15
    else:
        celsius = temp

    # 从摄氏转为目标单位
    if to_scale.lower() == 'f':
        return celsius * 9 / 5 + 32
    elif to_scale.lower() == 'k':
        return celsius + 273.15
    else:
        return celsius


print(f"37°C → {convert_temp(37, 'c', 'f'):.1f}°F")  # 98.6°F
print(f"212°F → {convert_temp(212, 'f', 'k'):.1f}K")  # 373.15K













def is_palindrome(s):
    """检查字符串是否为回文（忽略大小写和空格）"""
    s = ''.join(c.lower() for c in s if c.isalnum())
    return s == s[::-1]

print(is_palindrome("A man, a plan, a canal: Panama"))  # True













